//
//  XMGRecommandViewController.m
//  BuDeJie19
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//

#import "XMGRecommandViewController.h"
#import "XMGCategoryItem.h"
#import <MJExtension/MJExtension.h>
#import "XMGCategoryCell.h"
#import "XMGUserItem.h"
#import "XMGUserCell.h"
#import <MJRefresh/MJRefresh.h>
static NSString * const categoryID = @"category";
static NSString * const userID = @"user";
@interface XMGRecommandViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;
@property (weak, nonatomic) IBOutlet UITableView *userTableView;
@property (nonatomic, strong) NSArray *categorys;
@property (nonatomic, strong) XMGCategoryItem *selectedCategory;
@property (nonatomic, weak) AFHTTPSessionManager *mgr;
@end

@implementation XMGRecommandViewController
- (AFHTTPSessionManager *)mgr
{
    if (_mgr == nil) {
        _mgr = [AFHTTPSessionManager xmg_manager];
    }
    return _mgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"推荐关注";
    
    // 初始化tableVeiw
    [self setupTableView];
    
    // 加载分类数据
    [self loadCategoryData];
    
    // 用户tableVeiw添加上下拉刷新
    [self setupRefreshView];
}


- (void)setupRefreshView
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUserData)];
    _userTableView.mj_header = header;
    
    // 上拉
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUserData)];
    footer.automaticallyHidden = YES;
    _userTableView.mj_footer = footer;
}

- (void)setupTableView
{
    _categoryTableView.dataSource = self;
    _categoryTableView.delegate = self;
    
    _userTableView.dataSource = self;
    _userTableView.delegate = self;
    
    [self.categoryTableView registerNib:[UINib nibWithNibName:@"XMGCategoryCell" bundle:nil] forCellReuseIdentifier:categoryID];
    [self.userTableView registerNib:[UINib nibWithNibName:@"XMGUserCell" bundle:nil] forCellReuseIdentifier:userID];
    
    // 取消自动添加额外滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.categoryTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.userTableView.contentInset = self.categoryTableView.contentInset;
}

- (void)loadCategoryData
{
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager xmg_manager];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"category";
    parameters[@"c"] = @"subscribe";
    
    [mgr GET:XMGBaseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
        // 字典转模型
        _categorys = [XMGCategoryItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [_categoryTableView reloadData];
        
        // 默认选中分类tableView第0个cell
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        // 选中第0行
        [_categoryTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        
        // 主动去调用方法
        [self tableView:_categoryTableView didSelectRowAtIndexPath:indexPath];
        
//        NSLog(@"%@",responseObject);
//        [responseObject writeToFile:@"/Users/xmg5/Desktop/课堂共享/03-项目/1030/代码/14-推荐关注/recommand.plist" atomically:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

// 加载更多用户数据
- (void)loadMoreUserData
{
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"subscribe";
    // 获取当前分类ID
    parameters[@"category_id"] = _selectedCategory.id;
    parameters[@"page"] = @(_selectedCategory.page);
    
    [self.mgr GET:XMGBaseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 结束上拉刷新
        [_userTableView.mj_footer endRefreshing];
        
        _selectedCategory.page++;
        
        // 结束下拉刷新
        [_userTableView.mj_header endRefreshing];
        
        // 字典转模型
        NSArray *arr = [XMGUserItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        // 一定要使用addObjectsFromArray
        [_selectedCategory.users addObjectsFromArray:arr];
        
        [_userTableView reloadData];
        
        // 一定要放在reloadData后面
        // 超出总页数 隐藏上拉刷新
        _userTableView.mj_footer.hidden = _selectedCategory.page > _selectedCategory.total_page;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

// 加载最新用户数据
- (void)loadNewUserData
{
    _selectedCategory.page = 1;
    
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"subscribe";
    // 获取当前分类ID
    parameters[@"category_id"] = _selectedCategory.id;
    
    [self.mgr GET:XMGBaseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
        // 记录当前分类总页数
        _selectedCategory.total_page = [responseObject[@"total_page"] integerValue];
        
        _selectedCategory.page++;
        
        // 结束下拉刷新
        [_userTableView.mj_header endRefreshing];
        
        // 字典转模型
         _selectedCategory.users = [XMGUserItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [_userTableView reloadData];
        
        // 超出总页数 隐藏上拉刷新
        _userTableView.mj_footer.hidden = _selectedCategory.page > _selectedCategory.total_page;

//        NSLog(@"%@",responseObject);
//        [responseObject writeToFile:@"/Users/xmg5/Desktop/课堂共享/03-项目/1030/代码/14-推荐关注/user.plist" atomically:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - UITableViewDelegate
// 当用户点击cell的时候才会调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _categoryTableView) {
        
        // 记录下当前选择的分类模型
        _selectedCategory = _categorys[indexPath.row];
        
        [_userTableView reloadData];
        
        _userTableView.mj_footer.hidden = _selectedCategory.page > _selectedCategory.total_page;
        
        // 判断之前有没有加载过对应用户数据
        if (!_selectedCategory.users.count) {
            
            _userTableView.mj_footer.hidden = YES;
            
            // 加载右边TableView
            [_userTableView.mj_header beginRefreshing];
//            [self loadNewUserData];
        }
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _categoryTableView) return 44;
    
    return 60;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 分类
    if (tableView == _categoryTableView) return _categorys.count;
    
    // 用户
    return _selectedCategory.users.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _categoryTableView) { // 分类
        XMGCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:categoryID];
        
        cell.category = _categorys[indexPath.row];
        
        return cell;
    }
    
    // 用户
    XMGUserCell *cell = [tableView dequeueReusableCellWithIdentifier:userID];
    
    cell.user = _selectedCategory.users[indexPath.row];
    
    return cell;
    
}

@end
